// @algorithm @lc id=100280 lang=javascript
// @title ti-huan-kong-ge-lcof
// @test('We are happy.')="We%20are%20happy."
/**
 * @param {string} s
 * @return {string}
 */
var replaceSpace = function (s) {
  if (!s || s.length === 0) return '';

  const strArr = s.split('');

  let originLength = strArr.length;
  // 空格数量
  let numberOfBlank = 0;
  let i = 0;
  while (i < originLength) {
    if (strArr[i++] === ' ') numberOfBlank++;
  }
  // 新数组的长度
  let newLength = originLength + numberOfBlank * 2;
  // 扩充数组
  strArr.length = newLength;

  let originIndex = originLength - 1;
  let newIndex = newLength - 1;
  // 倒序复制数组内容
  while (originIndex >= 0 && originIndex < newIndex) {
    if (strArr[originIndex] === ' ') {
      strArr[newIndex--] = '0';
      strArr[newIndex--] = '2';
      strArr[newIndex--] = '%';
    } else {
      strArr[newIndex--] = strArr[originIndex];
    }
    originIndex--;
  }

  return strArr.join('');
};
